package com.gimi.cloud.jimi.common.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 发送http 请求并返回
 * 
 * @author luckchen
 * 
 *         2015-4-18 上午11:36:34
 */
public class HttpSender {

	private static HttpSender instance = new HttpSender();

	private HttpSender() {
	}

	public static HttpSender getInstance() {
		return instance;
	}

	/**
	 * 利用URL发起POST请求，并接收返回信息
	 * 
	 * @param url
	 *            请求URL
	 * @param params
	 *            请求参数
	 * @return 响应内容
	 * @throws Exception
	 */
	public String post(String url, String params) {
		if (!url.toLowerCase().startsWith("http://")) {
			return "非 http请求";
		}

		try {
			URL u = new URL(url);// 创建连接
			HttpURLConnection connection = (HttpURLConnection) u.openConnection();
			connection.setDoOutput(true);
//			System.setProperty("sun.net.client.defaultConnectTimeout", "15000");  
//			System.setProperty("sun.net.client.defaultReadTimeout", "15000");  
			connection.setConnectTimeout(15000);//设置超时
			connection.setReadTimeout(15000);//设置读取超时
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestMethod("POST"); // 设置请求方式
			connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
			connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
			connection.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJleHQiOjE1MDA0MzY1NzE5MDIsInVpZCI6IjI5MTk2OTQ1MiIsInVzZXJJZCI6Imx1Y2siLCJpYXQiOjE1MDA0MjkzNzE5MDJ9.RjhFZ4Ntvrvsk6I_AEdKJLg9EfEwgGhk00tag-ZJHFw");
			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
			out.append(params);
			out.flush();
			out.close();
			// 读取响应
			int length = (int) connection.getContentLength();// 获取长度
			InputStream is = connection.getInputStream();
			if (length>0) {
				byte[] data = new byte[length];
				
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ((readLen = is.read(temp)) > 0) {
					System.arraycopy(temp, 0, data, destPos, readLen);
					destPos += readLen;                                                                                                                                                                                                                                                                                                                  
				}
				String result = new String(data, "UTF-8"); // utf-8编码
				return result;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "{\"head\":{\"responseCode\":\"请求接口出错\"}}"; // 自定义错误信息
	}
	public String post2(String url, String params) {
		if (!url.toLowerCase().startsWith("http://")) {
			return "非 http请求";
		}

		try {
			URL u = new URL(url);// 创建连接
			HttpURLConnection connection = (HttpURLConnection) u.openConnection();
			connection.setDoOutput(true);
//			System.setProperty("sun.net.client.defaultConnectTimeout", "15000");
//			System.setProperty("sun.net.client.defaultReadTimeout", "15000");
			connection.setConnectTimeout(15000);//设置超时
			connection.setReadTimeout(15000);//设置读取超时
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestMethod("POST"); // 设置请求方式
			connection.setRequestProperty("Content-Type", "text/xml");
//			connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
//			connection.setRequestProperty("Content-Type", "application/j son"); // 设置发送数据的格式
//			connection.setRequestProperty("Authorization", "Bearer eyJhbGciOiJIUzI1NiJ9.eyJleHQiOjE1MDA0MzY1NzE5MDIsInVpZCI6IjI5MTk2OTQ1MiIsInVzZXJJZCI6Imx1Y2siLCJpYXQiOjE1MDA0MjkzNzE5MDJ9.RjhFZ4Ntvrvsk6I_AEdKJLg9EfEwgGhk00tag-ZJHFw");
			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
//			out.append(params);
			out.write(params);
//			out.append(params);
			out.flush();
			out.close();
			// 读取响应
			int length = (int) connection.getContentLength();// 获取长度
			length =10;
			InputStream is = connection.getInputStream();
			String sCurrentLine = "";
			String sTotalString = "";
//			if (code == 200)
//			{
//				java.io.InputStream is = httpConn.getInputStream();
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(is));
				while ((sCurrentLine = reader.readLine()) != null)
					if (sCurrentLine.length() > 0)
						sTotalString = sTotalString + sCurrentLine.trim();
//			} else
//			{
//				sTotalString = "远程服务器连接失败,错误代码:" + code;
//
//			}
			System.out.println("response:" + sTotalString);
////			if (length>0) {
//				byte[] data = new byte[length];
//
//				byte[] temp = new byte[512];
//				int readLen = 0;
//				int destPos = 0;
//				while ((readLen = is.read(temp)) > 0) {
//					System.arraycopy(temp, 0, data, destPos, readLen);
//					destPos += readLen;
//				}
//				String result = new String(sTotalString, "UTF-8"); // utf-8编码
				return sTotalString;
//			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "{\"head\":{\"responseCode\":\"请求接口出错\"}}"; // 自定义错误信息
	}
}
